<template>
  <div style="margin-left: 25px; margin-top: 15px">
    <!--查询条件-->
    <el-form :inline="true" :model="search" class="demo-form-inline">
      <table>
        <tr>
          <td>
            <el-form-item label="分娩日期">
              <el-date-picker v-model="search.date" type="datetimerange" range-separator="-"
                start-placeholder="Start date" end-placeholder="End date" value-format="YYYY-MM-DD"
                style="width: 240px" />
            </el-form-item>
            <el-form-item label="种母耳号">
              <el-input v-model="search.Earbugles" clearable />
            </el-form-item>
            <el-form-item label="转出栋舍">
              <el-select v-model="search.OutBuildings" clearable style="width: 200px">
                <el-option :label="item.Name" :value="item.Name" v-for="item in InDormList" :key="item.Id" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="danger" size="default" :icon="Search" @click="GetdeliceryList">查询</el-button>
            </el-form-item><br />
          </td>
        </tr>
        <tr>
          <td>
            <el-form-item label="转入栋舍">
              <el-select v-model="search.InBuildings" clearable style="width: 200px">
                <el-option :label="item.Name" :value="item.Name" v-for="item in InDormList" :key="item.Id" />
              </el-select>
            </el-form-item>
            <el-form-item label="窝号" style="margin-left: 70px; margin-right: 47px">
              <el-input v-model="search.nestNumber" clearable style="width: 217px" />
            </el-form-item>
            <el-form-item label="负责人">
              <el-select v-model="search.head" clearable style="width: 200px">
                <el-option :label="item.name" :value="item.name" v-for="item in HeadList" :key="item.id" />
              </el-select>
            </el-form-item>
          </td>
        </tr>
      </table>
    </el-form>

    <!-- 操作按钮 -->
    <div style="margin-top: 9px">
      <el-button type="danger" size="default" :icon="Plus" @click="openCreate">新增</el-button>
      <el-button type="danger" size="default" :icon="Delete" @click="DelAll">删除</el-button>
    </div>

    <!-- 列表 -->
    <div style="margin-top: 25px">
      <el-table :data="deliceryList" stripe style="width: 85%" @selection-change="GetDeliveryIds">
        <el-table-column type="selection" width="35" fixed align="center" />
        <el-table-column label="序号" align="center" fixed>
          <template #default="a">
            <span>{{ a.$index + (page.pageIndex - 1) * page.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="earbugles" label="种母耳号" align="center" width="130" />
        <el-table-column prop="deliveryDate" label="分娩日期⬇" align="center" width="130">
          <template v-slot="a">
            <span v-if="a.row.deliveryDate"> {{ a.row.deliveryDate.substring(0, 10) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="gestationDays" label="妊娠天数" align="center" width="130" />
        <el-table-column prop="difficultyOfDelivery" label="分娩难易" align="center" width="130" />
        <el-table-column prop="maternity" label="母性" align="center" width="130" />
        <el-table-column prop="lactation" label="泌乳" align="center" width="130" />
        <el-table-column prop="mastitis" label="乳房炎" align="center" width="130" />
        <el-table-column label="窝总羔数" align="center" width="130">
          <template v-slot="a">
            <span>{{ (a.row.healthyLamb + a.row.weakLamb + a.row.malformation + a.row.deadFetus + a.row.malformedFetus +
              a.row.mummyNumber)
              }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="nestTotalWeight" label="窝总重(公斤)" align="center" width="130">
          <template v-slot="a">
            <span v-if="a.row.nestTotalWeight">{{ a.row.nestTotalWeight.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="liveLamb" label="活羔总数" align="center" width="130">
          <template v-slot="a">
            <span v-if="a.row.liveLamb"> {{ a.row.liveLamb }}</span>
            <span v-else> ---</span>
          </template>
        </el-table-column>
        <el-table-column label="活羔总重" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.liveLamb">{{ (a.row.nestTotalWeight / (a.row.healthyLamb + a.row.weakLamb +
              a.row.malformation + a.row.deadFetus
              + a.row.malformedFetus + a.row.mummyNumber) * a.row.liveLamb).toFixed(2) }}公斤</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="活羔均重" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.liveLamb">{{ ((a.row.nestTotalWeight / (a.row.healthyLamb + a.row.weakLamb +
              a.row.malformation + a.row.deadFetus
              + a.row.malformedFetus + a.row.mummyNumber) * a.row.liveLamb) / a.row.liveLamb).toFixed(2) }}公斤</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="死羔总重" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.deadFetus">{{ (a.row.nestTotalWeight / (a.row.healthyLamb + a.row.weakLamb +
              a.row.malformation + a.row.deadFetus
              + a.row.malformedFetus + a.row.mummyNumber) * a.row.deadFetus).toFixed(2) }}公斤</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column label="死羔均重" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.deadFetus">{{ ((a.row.nestTotalWeight / (a.row.healthyLamb + a.row.weakLamb +
              a.row.malformation + a.row.deadFetus
              + a.row.malformedFetus + a.row.mummyNumber) * a.row.deadFetus) / a.row.deadFetus).toFixed(2) }}公斤</span>
            <span v-else>---</span>
          </template>
        </el-table-column>
        <el-table-column prop="fatSheepLot" label="肥羊批次" align="center" width="130px" />
        <el-table-column prop="healthyLamb" label="健羔数" align="center" width="130px" />
        <el-table-column prop="weakLamb" label="弱羔数" align="center" width="130px" />
        <el-table-column prop="malformation" label="畸形数" align="center" width="130px" />
        <el-table-column prop="deadFetus" label="死胎数" align="center" width="130px" />
        <el-table-column prop="malformedFetus" label="畸胎数" align="center" width="130px" />
        <el-table-column prop="mummyNumber" label="木乃伊数" align="center" width="130px" />
        <el-table-column prop="nestNumber" label="窝号" align="center" width="130px" />
        <el-table-column prop="lambSex" label="性别" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.lambSex">公</span>
            <span v-else>母</span>
          </template>
        </el-table-column>
        <el-table-column prop="currentBuilding" label="当前栋舍" align="center" width="130px" />
        <el-table-column prop="currentField" label="当前栏位" align="center" width="130px" />
        <el-table-column prop="originallyDorm" label="转入栋舍" align="center" width="130px" />
        <el-table-column prop="originallyColumns" label="转入栏位" align="center" width="130px" />
        <el-table-column prop="createBy" label="创建人" align="center" />
        <el-table-column prop="createDate" label="创建时间" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.createDate"> {{ a.row.createDate.substring(0, 10) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="修改人" align="center" />
        <el-table-column prop="updateDate" label="修改时间" align="center" width="130px">
          <template v-slot="a">
            <span v-if="a.row.updateDate"> {{ a.row.updateDate.substring(0, 10) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="130px">
          <template v-slot="a">
            <el-link type="primary" style="margin-right: 15px" @click="openUpdate(a.row.deliveryId)">编辑</el-link>
            <el-link type="primary" @click="deliveryDel(a.row.deliveryId)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <table style="margin: auto; margin-left: 300px; margin-top: 25px">
      <tbody>
        <tr>
          <td>
            <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
              :page-sizes="[15, 20, 35, 50]" :background="true" layout="total, slot,sizes" :total="page.totalCount"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
              <span>，共{{ page.pageCount }}页，当前第{{ page.pageIndex }}/{{
                page.pageCount
              }}页</span>
            </el-pagination>
          </td>
          <td>
            <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
              :page-sizes="[15, 20, 35, 50]" :background="true" layout="slot, prev, pager, next"
              :total="page.totalCount" @size-change="handleSizeChange" @current-change="handleCurrentChange"
              prev-text="上一页" next-text="下一页">
              <button class="btn-prev" @click="handleCurrentChange(1)" :disabled="page.pageIndex == 1">
                首页
              </button>
            </el-pagination>
          </td>
          <td>
            <el-pagination v-model:current-page="page.pageIndex" v-model:page-size="page.pageSize"
              :page-sizes="[15, 20, 35, 50]" :background="true" layout="slot, jumper" :total="page.totalCount"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" prev-text="上一页" next-text="下一页">
              <button class="btn-next" @click="handleCurrentChange(page.pageCount)"
                :disabled="page.pageIndex == page.pageCount">
                尾页
              </button>
            </el-pagination>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 弹出层添加 -->
    <el-dialog v-model="dialogVisible" title="添加分娩信息" width="1300" style="height: 600px">
      <span>
        <div class="dialog-footer">
          <div style="margin-left: 25px; margin-top: 15px">
            <div>
              <el-button type="danger" size="default" :icon="Plus" @click="AddRow"
                v-show="deliveryInfo.deliveryId == 0">新增</el-button>
              <el-button type="danger" size="default" :icon="Document" @click="CreatedeliveryInfo"
                v-show="deliveryInfo.deliveryId == 0">保存</el-button>
              <el-button type="danger" size="default" :icon="Document" v-show="deliveryInfo.deliveryId != 0"
                @click="deliveryUpd">修改</el-button>
            </div>
            <div style="margin-top: 25px; margin-left: 25px">
              <el-form :inline="true" :model="deliveryInfo" class="demo-form-inline">
                <el-form-item label="*负责人">
                  <el-select v-model="deliveryInfo.head" filterable placeholder="请选择" style="width: 110px" @change="">
                    <el-option v-for="item in HeadList" :key="item.name" :label="item.name" :value="item.name" />
                  </el-select>
                </el-form-item>
                <el-form-item label="*分娩日期">
                  <el-date-picker v-model="deliveryInfo.deliveryDate" type="date" placeholder="请选择" clearable
                    value-format="YYYY-MM-DD" style="width: 150px" />
                </el-form-item>
              </el-form>
            </div>
            <div style="margin-top: 35px">
              <el-table style="width: 90%" :data="RowList">
                <el-table-column label="序号" align="center">
                  <template #default="a">
                    <span>{{ a.$index + (page.pageIndex - 1) * page.pageSize + 1 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="*耳号" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.earbugles" filterable placeholder="请输入" style="width: 98px"
                        @change="GetSheepInfo">
                        <el-option v-for="item in ZMEarList" :key="item.name" :label="item.name" :value="item.name" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="妊娠天数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <span v-if="activeIndex == a.$index">
                        <el-input v-model="deliveryInfo.gestationDays" style="width: 98px" />
                      </span>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="*分娩难易" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.difficultyOfDelivery" clearable style="width: 98px">
                        <el-option label="顺产" value="顺产" />
                        <el-option label="难产" value="难产" />
                        <el-option label="助产" value="助产" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="*肥羊批次" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.fatSheepLot" clearable style="width: 98px">
                        <el-option label="乳羊" value="乳羊" />
                        <el-option label="大肥" value="大肥" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="母性" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.maternity" clearable style="width: 98px">
                        <el-option label="1分" value="1分" />
                        <el-option label="2分" value="2分" />
                        <el-option label="3分" value="3分" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="泌乳" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.lactation" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="乳房炎" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.mastitis" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="*窝号" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.nestNumber" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="健羔数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.healthyLamb" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="弱羔数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.weakLamb" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="畸形数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.malformation" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="死胎数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.deadFetus" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="木乃伊数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.mummyNumber" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="畸胎数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.malformedFetus" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="活羔数" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.liveLamb" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="窝总重(公斤)" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.nestTotalWeight" style="width: 98px" />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="性别" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.lambSex" clearable style="width: 98px">
                        <el-option label="公" :value="true" />
                        <el-option label="母" :value="false" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="当前栋舍" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.currentBuilding" style="width: 98px" readonly />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="当前栏位" align="center" width="130">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-input v-model="deliveryInfo.currentField" style="width: 98px" readonly />
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="*转入栋舍" align="center" width="135">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.originallyDorm" clearable style="width: 125px"
                        @change="GetCreateInColumnList">
                        <el-option :label="item.Name" :value="item.Name" v-for="item in CreateInDormList"
                          :key="item.Id" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="转入栏位" align="center" width="135">
                  <template v-slot="a">
                    <span v-if="activeIndex == a.$index">
                      <el-select v-model="deliveryInfo.originallyColumns" clearable style="width: 125px">
                        <el-option :label="item.Name" :value="item.Name" v-for="item in CreateInColumnList"
                          :key="item.Id" />
                      </el-select>
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Document, Delete, Back, Search } from "@element-plus/icons-vue";
import Enumerable from "linq";
import http from "@/http";



//打开修改弹窗
const openUpdate = (id: any) => {
  dialogVisible.value = true;
  RowList.value = [];
  AddRow();
  http.get("RouteRead/api/Deliverys/BackfillDelivery?Id=" + id).then(x => {
    var info = x.data;
    deliveryInfo.createBy = info.createBy;
    deliveryInfo.createDate = info.createDate;
    deliveryInfo.updateBy = info.updateBy;
    deliveryInfo.updateDate = info.updateDate;
    deliveryInfo.isDel = info.isDel;
    deliveryInfo.deliveryId = info.deliveryId;
    deliveryInfo.deliveryDate = info.deliveryDate;
    deliveryInfo.head = info.head;
    deliveryInfo.earbugles = info.earbugles;
    deliveryInfo.gestationDays = info.gestationDays;
    deliveryInfo.difficultyOfDelivery = info.difficultyOfDelivery;
    deliveryInfo.fatSheepLot = info.fatSheepLot;
    deliveryInfo.lactation = info.lactation;
    deliveryInfo.lambSex = info.lambSex;
    deliveryInfo.liveLamb = info.liveLamb;
    deliveryInfo.malformation = info.malformation;
    deliveryInfo.malformedFetus = info.malformedFetus;
    deliveryInfo.mastitis = info.mastitis;
    deliveryInfo.maternity = info.maternity;
    deliveryInfo.mummyNumber = info.mummyNumber;
    deliveryInfo.nestNumber = info.nestNumber;
    deliveryInfo.nestTotalWeight = info.nestTotalWeight;
    deliveryInfo.originallyColumns = info.originallyColumns;
    deliveryInfo.originallyDorm = info.originallyDorm;
    deliveryInfo.gestationDays = info.gestationDays;
    deliveryInfo.currentBuilding = info.currentBuilding;
    deliveryInfo.currentField = info.currentField;
    deliveryInfo.deadFetus = info.deadFetus;
    deliveryInfo.healthyLamb = info.healthyLamb;
    deliveryInfo.weakLamb = info.weakLamb;

  })
}
const deliveryUpd = () => {//根据耳号获取种母历史记录信息
  http.get("RouteRead/api/Historys/HistoryEarsel?EarNumber=" + deliveryInfo.earbugles).then(res => {
    var info = res.data;

    SheepUpd.earNumber = deliveryInfo.earbugles;
    SheepUpd.cottage = deliveryInfo.originallyDorm;
    SheepUpd.field = deliveryInfo.originallyColumns;
    http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)

    http.put("Kroute/api/Deliverys/DeliverUpdate", deliveryInfo).then(x => {
      if (x.data > 0) {
        ElMessage.success("修改分娩信息成功")
        dialogVisible.value = false;
        GetdeliceryList();


        //更改档案的繁殖状态
        http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + deliveryInfo.earbugles).then(res => {
          var form = res.data;
          form.reproductiveState = 8;
          http.put("Mroute/api/SheepFile/SheepFileConditionUpdate", form)
        })

        info.deliveryDate = deliveryInfo.deliveryDate;//分娩日期
        info.healthyLambNumber = deliveryInfo.healthyLamb;//健羔数
        info.weakLambNumber = deliveryInfo.weakLamb;//弱羔数
        info.deformityNumber = deliveryInfo.malformation;//畸形数
        info.stillbirthNumber = deliveryInfo.deadFetus;//死胎数
        info.mummyNumber = deliveryInfo.mummyNumber;//木乃伊数
        info.freaksNumber = deliveryInfo.malformedFetus;//畸胎数
        //更改种母历史记录
        http.post("Kroute/api/Historys/HistoryCreate", info);

      } else {
        ElMessage.error("修改分娩信息失败")
      }
    })
  })
}


//批量删除
var deliveryIds = ref("");
const GetDeliveryIds = (ids: any) => {
  deliveryIds.value = "";
  for (let index = 0; index < ids.length; index++) {
    deliveryIds.value += ids[index].sdId + ",";
  }
}
const AllOronly = ref(false);
const DelAll = () => {
  AllOronly.value = true;
  deliveryDel(deliveryIds.value.substring(0, deliveryIds.value.length - 1));
}

//删除转舍信息
const deliveryDel = (id: any) => {
  ElMessageBox.confirm(
    '确定要删除吗?',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'error',
    }
  )
    .then(() => {
      http.delete("Kroute/api/Deliverys/DeliveryDelete?Ids=" + id).then(x => {
        if (x.data > 0) {
          if (AllOronly.value == true) {
            AllOronly.value = false;
            var ids = id.split(",");
            ids.forEach((a: any) => {
              http.get("RouteRead/api/Deliverys/BackfillDelivery?Id=" + a).then(x => {
                SheepUpd.earNumber = x.data.earbugles;
                SheepUpd.cottage = x.data.originallyDorm;
                SheepUpd.field = x.data.originallyColumns;
                http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)
              })
            });
          } else {
            http.get("RouteRead/api/Deliverys/BackfillDelivery?Id=" + id).then(x => {
              SheepUpd.earNumber = x.data.earbugles;
              SheepUpd.cottage = x.data.currentBuilding;
              SheepUpd.field = x.data.currentField;
              http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)
            })
          }
          ElMessage.success("删除成功")
          GetdeliceryList();
        } else {
          ElMessage.error("删除失败")
        }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
      })
    })
}



//种母分娩信息集合
const deliceryList = ref([]);
const GetdeliceryList = () => {
  var dates = "";
  if (search.value.date) {
    dates = search.value.date.join(",").toString();
  }
  http.get("RouteRead/api/Deliverys/GetDelivery", {
    params: {
      pageIndex: page.pageIndex,
      pageSize: page.pageSize,
      InDate: dates,
      Earbugles: search.value.Earbugles,
      OutBuildings: search.value.OutBuildings,
      InBuildings: search.value.InBuildings,
      nestNumber: search.value.nestNumber,
      head: search.value.head,
    },
  })
    .then((res) => {
      deliceryList.value = res.data.datas;
      page.totalCount = res.data.totalCount;
      page.pageCount = res.data.pageCount;
    });
};

interface selectList {
  id: "";
  name: "";
}
//获取负责人信息
const HeadList = ref<selectList[]>([]);
const GetHeadList = () => {
  http.get("Readroute/api/StaffInfo/GetStaff").then((x) => {
    HeadList.value = x.data;
  });
};

//查询条件
const search = ref({
  date: [],
  Earbugles: "",
  OutBuildings: "",
  InBuildings: "",
  nestNumber: "",
  head: "",
});
//分页信息
const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  pageCount: 0,
});
const handleSizeChange = (val: any) => {
  page.pageSize = val;
};
const handleCurrentChange = (val: any) => {
  page.pageIndex = val;
};

//根据耳号获取羊只档案信息
const GetSheepInfo = () => {
  http
    .get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + deliveryInfo.earbugles)
    .then((x) => {
      http
        .get(
          "RouteRead/api/Breedings/GetBreedingForEar?EarNumber=" + deliveryInfo.earbugles
        )
        .then((res) => {
          var maxDate = Enumerable.from(res.data).max((a: any) => a.breedingDate);
          deliveryInfo.gestationDays = DateDiffer(maxDate);
        });

      if (x.data.sex == 1) {
        deliveryInfo.lambSex = true;
      } else {
        deliveryInfo.lambSex = false;
      }
      deliveryInfo.currentBuilding = x.data.cottage;
      deliveryInfo.currentField = x.data.field;
    });
};

//计算日期之间的天数
const DateDiffer = (Date_end: any) => {
  //date1结束时间
  let date1 = new Date(Date_end);
  //date2当前时间
  let date2 = new Date();
  // date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
  // date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
  const diff = date2.getTime() - date1.getTime(); //目标时间减去当前时间
  const diffDate = diff / (24 * 3600 * 1000); //计算当前时间与结束时间之间相差天数
  return Math.ceil(diffDate);
};

//新增行操作
var activeIndex = ref(-1);
var RowList = ref<{}[]>([]);
const AddRow = () => {
  var newRow = {
    deliveryId: 0,
    earbugles: "",
    head: null,
    deliveryDate: null,
    gestationDays: null,
    difficultyOfDelivery: null,
    fatSheepLot: null,
    maternity: null,
    lactation: null,
    mastitis: null,
    nestNumber: null,
    healthyLamb: 0,
    weakLamb: 0,
    malformation: 0,
    deadFetus: 0,
    mummyNumber: 0,
    malformedFetus: 0,
    liveLamb: 0,
    nestTotalWeight: null,
    lambSex: true,
    currentBuilding: null,
    currentField: null,
    originallyDorm: null,
    originallyColumns: null,
  };
  RowList.value.push(newRow);
  activeIndex.value = RowList.value.length - 1;
};

//添加用种母分娩信息
const dialogVisible = ref(false);
const openCreate = () => {
  dialogVisible.value = true;
};

interface deliveryInt {
  createBy: "string";
  createDate: "2024-05-10T03:47:55.189Z";
  updateBy: "string";
  updateDate: "2024-05-10T03:47:55.189Z";
  isDel: false;
  deliveryId: 0;
  earbugles: "";
  head: null;
  deliveryDate: null;
  gestationDays?: number;
  difficultyOfDelivery: null;
  fatSheepLot: null;
  maternity: null;
  lactation: null;
  mastitis: null;
  nestNumber: null;
  healthyLamb?: number;
  weakLamb?: number;
  malformation?: number;
  deadFetus?: number;
  mummyNumber?: number;
  malformedFetus?: number;
  liveLamb?: number;
  nestTotalWeight?: number;
  lambSex: boolean;
  currentBuilding: null;
  currentField: null;
  originallyDorm: null;
  originallyColumns: null;
}
const deliveryInfo = reactive(
  {
    "createBy": "string",
    "createDate": "2024-05-11T00:55:18.665Z",
    "updateBy": "string",
    "updateDate": "2024-05-11T00:55:18.665Z",
    "isDel": false,
    "deliveryId": 0,
    "earbugles": "",
    "head": "",
    "deliveryDate": "",
    "gestationDays": null,
    "difficultyOfDelivery": "",
    "fatSheepLot": "",
    "maternity": "",
    "lactation": "",
    "mastitis": "",
    "nestNumber": "",
    "healthyLamb": 0,
    "weakLamb": 0,
    "malformation": 0,
    "deadFetus": 0,
    "mummyNumber": 0,
    "malformedFetus": 0,
    "liveLamb": 0,
    "nestTotalWeight": 0,
    "lambSex": true,
    "currentBuilding": "",
    "currentField": "",
    "originallyDorm": null,
    "originallyColumns": null,
  }
)


const CreatedeliveryInfo = () => {
  //根据耳号获取种母历史记录信息
  http.get("RouteRead/api/Historys/HistoryEarsel?EarNumber=" + deliveryInfo.earbugles).then(res => {
    var info = res.data;


    if (!deliveryInfo.head) {
      ElMessage.error("请选择负责人");
      return;
    }
    if (!deliveryInfo.deliveryDate) {
      ElMessage.error("请选择分娩日期");
      return;
    }
    if (!deliveryInfo.earbugles) {
      ElMessage.error("请输入耳号");
      return;
    }
    if (!deliveryInfo.difficultyOfDelivery) {
      ElMessage.error("请选择分娩难易");
      return;
    }
    if (!deliveryInfo.fatSheepLot) {
      ElMessage.error("请选择肥羊批次");
      return;
    }
    if (!deliveryInfo.nestNumber) {
      ElMessage.error("请输入窝号");
      return;
    }

    //更改羊只栋舍信息
    SheepUpd.earNumber = deliveryInfo.earbugles;
    SheepUpd.cottage = deliveryInfo.originallyDorm;
    SheepUpd.field = deliveryInfo.originallyColumns;
    http.put("Mroute/api/SheepFile/SheepFileConditionAuricleUpdate", SheepUpd)

    http.post("Kroute/api/Deliverys/DeliveryCreate", deliveryInfo).then((res) => {
      if (res.data > 0) {
        ElMessage.success("保存种母分娩信息成功");
        dialogVisible.value = false;
        GetdeliceryList();

        //更改档案的繁殖状态
        http.get("MYroute/api/SheepFile/SheepFileConditionFinds?card=" + deliveryInfo.earbugles).then(res => {
          var form = res.data;
          form.reproductiveState = 8;
          http.put("Mroute/api/SheepFile/SheepFileConditionUpdate", form)
        })

        info.deliveryDate = deliveryInfo.deliveryDate;//分娩日期
        info.healthyLambNumber = deliveryInfo.healthyLamb;//健羔数
        info.weakLambNumber = deliveryInfo.weakLamb;//弱羔数
        info.deformityNumber = deliveryInfo.malformation;//畸形数
        info.stillbirthNumber = deliveryInfo.deadFetus;//死胎数
        info.mummyNumber = deliveryInfo.mummyNumber;//木乃伊数
        info.freaksNumber = deliveryInfo.malformedFetus;//畸胎数
        //更改种母历史记录
        http.post("Kroute/api/Historys/HistoryCreate", info);

      } else {
        ElMessage.error("保存种母分娩信息失败");
      }
    });
  })
};

//查询使用的栋舍下拉框
const InDormList = ref<
  {
    Id: "";
    Name: "";
  }[]
>([]);
const GetInDormList = () => {
  http.get("OrganizationRead/api/Cottage/HandleGetCot").then((x) => {
    InDormList.value = x.data;
  });
};

//添加用转入栋舍和栏位
const CreateInDormList = ref<
  {
    Id: "";
    Name: "";
  }[]
>([]);
const GetCreateInDormList = () => {
  http.get("OrganizationRead/api/Cottage/HandleGetCot").then((x) => {
    CreateInDormList.value = x.data;
  });
};
const CreateInColumnList = ref<
  {
    Id: "";
    Name: "";
  }[]
>([]);
const GetCreateInColumnList = () => {
  if (deliveryInfo.originallyDorm) {
    http
      .get(
        "OrganizationRead/api/Field/HandleGetSheepFarm?Id=" + deliveryInfo.originallyDorm
      )
      .then((x) => {
        CreateInColumnList.value = x.data;
      });
  }
};

//获取种公种母后裔耳标（分类后）
const ZMEarList = ref<
  {
    name: "";
  }[]
>([]);
const ZGEarList = ref<
  {
    name: "";
  }[]
>([]);
const HYEarList = ref<
  {
    name: "";
  }[]
>([]);
const GetEarList = () => {
  http.get("MYroute/api/SheepFile/SheepFileConditionarchives").then((x) => {
    x.data.forEach((a: any) => {
      if (a.sheepType == "种母" && a.reproductiveState == "妊娠") {
        ZMEarList.value.push({
          name: a.card,
        });
      } else if (a.sheepType == "种公") {
        ZGEarList.value.push({
          name: a.card,
        });
      } else {
        HYEarList.value.push({
          name: a.card,
        });
      }
    });
  });
};

//修改羊只档案信息
var SheepUpd = reactive({
  earNumber: "",
  cottage: null,
  field: null,
})

onMounted(() => {
  //获取耳号信息
  GetEarList();
  //获取查询用的栋舍信息
  GetInDormList();
  //获取负责人
  GetHeadList();
  //添加用转入栋舍
  GetCreateInDormList();
  //获取种母分娩信息列表
  GetdeliceryList();
});
</script>

<style></style>
